<?php

namespace App\Models;

use DateTimeInterface;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class VueAdmin extends Authenticatable
{
    use HasFactory, Notifiable;

    protected $table = 'la_vue_admins';

    protected $guarded = [];

    protected $dateFormat = 'U';

    /**
     * The attributes that should be hidden for arrays.
     *
     * @var array
     */
    protected $hidden = [
        'password',
        'remember_token',
    ];

    /**
     * The attributes that should be cast to native types.
     *
     * @var array
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    protected function serializeDate(DateTimeInterface $date)
    {
        return $date->format('Y-m-d H:i:s');
    }

    public static function _after_insert($data)
    {
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            File::where('file_url', $data['avatar'])->update(['related_id' => $data['id'], 'related_table' => 'admins', 'status' => 1]);
        }
    }

    public static function _after_update($data)
    {
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            // 处理删除掉的文件
            File::where(['related_id' => $data['id'], 'related_table' => 'admins'])->where('file_url', '<>', $data['avatar'])->update(['status' => 0]);

            File::where('file_url', $data['avatar'])->update(['related_id' => $data['id'], 'related_table' => 'admins', 'status' => 1]);
        }
    }

    public static function _after_delete($id)
    {
        $data = self::find($id);
        // 头像
        if (isset($data['avatar']) && !empty($data['avatar'])) {
            File::where('file_url', $data['avatar'])->update(['status' => 0]);
        }
    }

    /**
     * 格式化列表数据
     */
    public static function formatDatas($list, $params = '')
    {

        foreach ($list as &$item) {
            $item = self::formatItem($item, $params);
        }

        return $list;
    }

    /**
     * 格式化单个数据
     */
    public static function formatItem($item, $params = '')
    {
        if (!$item) {
            return '';
        }

        if ($item['avatar']) {
            $item['full_avatar'] = full_file_url($item['avatar']);
        } else {
            $item['full_avatar'] = letter_avatar($item['username']);
        }
        if ($item['status'] == 1) {
            $item['status_name'] = '正常';
        } else {
            $item['status_name'] = '禁用';
        }

        if (isset($params['source']) && $params['source'] == 'backend') {
            // 角色
            /*if ($item['type'] == 0) {
                $item['role_names'] = '超级管理员';
            } else {
                $roleIds = VueAdminRoleUser::where('admin_id', $item['id'])->pluck('role_id')->toArray();
                $roleNames = VueAdminRole::whereIn('id', $roleIds)->pluck('name')->toArray();
                $item['role_ids'] = $roleIds;
                $item['role_names'] = $roleNames ? implode('、', $roleNames) : '';
            }*/
            $roleIds = VueAdminRoleUser::where('admin_id', $item['id'])->pluck('role_id')->toArray();
            $roleNames = VueAdminRole::whereIn('id', $roleIds)->pluck('name')->toArray();
            $item['role_ids'] = $roleIds;
            $item['role_names'] = $roleNames ? implode('、', $roleNames) : '';
        } else {
            //
        }

        return $item;
    }

    /**
     * 删除
     */
    public static function doDelete($id)
    {
        AdminRoleUser::where('admin_id', $id)->delete();

        return self::where('id', $id)->delete();
    }

    /**
     * 获取管理员的路由菜单
     */
    public function getMenus($adminId, $isRoute = false)
    {
        $cacheKey = 'all_menus-' . $adminId;
        if ($isRoute) {
            $cacheKey = 'route_menus-' . $adminId;
        }
        $route_menus = cache($cacheKey);
        if (!$route_menus) {
            $adminMenuMdl = new \App\Models\VueAdminMenu();
            $adminRoleUserMdl = new \App\Models\VueAdminRoleUser();

            // 角色
            $roles = $adminRoleUserMdl->where('admin_id', $adminId)->with(['adminRole'])->get()->toArray();
            $accessStr = '';
            foreach ($roles as $item) {
                //$adminRole = $item->adminRole; // 对象的写法
                $adminRole = $item['admin_role'];
                if (!empty($adminRole)){
                    $accessStr .= ',' . $adminRole['access'];
                }
            }
            // 权限
            if ($accessStr != ''){
                $access = array_unique(explode(',', substr($accessStr, 1)));
            }

            $menuWhere = [
                //['id', 'in', $access],
                ['status', '=', 1]
            ];
            if ($isRoute) {
                $menuWhere[] = ['is_route', '=', 1];
            }
            if (!empty($access)) {
                $menuDatas = $adminMenuMdl->where($menuWhere)->whereIn('id', $access)->orderBy('sorting', 'ASC')->get()->toArray();
            } else {
                $menuDatas = [];
                if($adminId == 1){
                    $menuDatas = $adminMenuMdl->where($menuWhere)->orderBy('sorting', 'ASC')->get()->toArray();
                }
            }
            $route_menus = [];
            foreach ($menuDatas as $menuData) {
                $route_menus[] = [
                    'id' => $menuData['id'],
                    'parent_id' => $menuData['parent_id'],
                    'name' => $menuData['name'],
                    'app' => $menuData['app'],
                    'controller' => $menuData['controller'],
                    'action' => $menuData['action'],
                    'route' => $menuData['route'],
                    'type' => $menuData['type'],
                    'icon' => $menuData['icon'],
                    'sorting' => $menuData['sorting'],
                    'icon2' => $menuData['icon2'],
                ];
            }

            // cache([$cacheKey => $route_menus], 3600 * 6);
        }

        return $route_menus;
    }
}
